using Microsoft.AspNetCore.Mvc;
using Sheep_Breeding.ErrorCode;
using Sheep_Breeding.Write.Api.DTOs;
using Sheep_Breeding.Write.Api.OperationServices.IServices;

namespace Sheep_Breeding.Write.Api.Controllers
{
    /// <summary>
    /// 羊只采购控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class SheepPurchaseController : ControllerBase
    {
        private readonly ILogger<SheepPurchaseController> _logger;
        private readonly ISheepPurchaseServices _sheepPurchaseServices;

        public SheepPurchaseController(
            ILogger<SheepPurchaseController> logger,
            ISheepPurchaseServices sheepPurchaseServices)
        {
            _logger = logger;
            _sheepPurchaseServices = sheepPurchaseServices;
        }

        /// <summary>
        /// 添加羊只采购信息
        /// </summary>
        /// <param name="dto">羊只采购信息</param>
        /// <returns>操作结果</returns>
        [HttpPost("add")]
        public async Task<ApiResult> AddSheepPurchase([FromBody] AddSheepPurchaseDto dto)
        {
            _logger.LogInformation("开始添加羊只采购信息");
            
            try
            {
                if (!ModelState.IsValid)
                {
                    _logger.LogWarning("添加羊只采购信息时模型验证失败");
                    return new ApiResult { msg = "请求参数验证失败", code = ApiREunm.Fail };
                }

                var result = await _sheepPurchaseServices.AddSheepPurchase(dto);
                _logger.LogInformation("羊只采购信息添加完成");
                
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加羊只采购信息时发生异常: {Message}", ex.Message);
                _logger.LogError("异常堆栈: {StackTrace}", ex.StackTrace);
                return new ApiResult 
                { 
                    msg = $"添加羊只采购信息失败: {ex.Message}", 
                    code = ApiREunm.Fail 
                };
            }
        }

        /// <summary>
        /// 更新羊只采购信息
        /// </summary>
        /// <param name="dto">更新的羊只采购信息</param>
        /// <returns>操作结果</returns>
        [HttpPut("update")]
        public async Task<ApiResult> UpdateSheepPurchase([FromBody] UpdateSheepPurchaseDto dto)
        {
            _logger.LogInformation("开始更新羊只采购信息，ID: {Id}", dto.Id);
            
            try
            {
                if (!ModelState.IsValid)
                {
                    _logger.LogWarning("更新羊只采购信息时模型验证失败");
                    return new ApiResult { msg = "请求参数验证失败", code = ApiREunm.Fail };
                }

                var result = await _sheepPurchaseServices.UpdateSheepPurchase(dto);
                _logger.LogInformation("羊只采购信息更新完成，ID: {Id}", dto.Id);
                
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新羊只采购信息时发生异常，ID: {Id}, Message: {Message}", dto.Id, ex.Message);
                return new ApiResult 
                { 
                    msg = "更新羊只采购信息失败，请稍后重试", 
                    code = ApiREunm.Fail 
                };
            }
        }

        /// <summary>
        /// 删除羊只采购信息（逻辑删除）
        /// </summary>
        /// <param name="dto">删除的羊只采购信息</param>
        /// <returns>操作结果</returns>
        [HttpDelete("delete")]
        public async Task<ApiResult> DeleteSheepPurchase([FromQuery] DeleteSheepPurchaseDto dto)
        {
            _logger.LogInformation("开始删除羊只采购信息，ID: {Id}", dto.Id);
            
            try
            {
                if (!ModelState.IsValid)
                {
                    _logger.LogWarning("删除羊只采购信息时模型验证失败");
                    return new ApiResult { msg = "请求参数验证失败", code = ApiREunm.Fail };
                }

                var result = await _sheepPurchaseServices.DeleteSheepPurchase(dto);
                _logger.LogInformation("羊只采购信息删除完成，ID: {Id}", dto.Id);
                
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除羊只采购信息时发生异常，ID: {Id}, Message: {Message}", dto.Id, ex.Message);
                return new ApiResult 
                { 
                    msg = "删除羊只采购信息失败，请稍后重试", 
                    code = ApiREunm.Fail 
                };
            }
        }

        /// <summary>
        /// 查询羊只采购信息
        /// </summary>
        /// <param name="dto">查询条件</param>
        /// <returns>查询结果</returns>
        [HttpGet("search")]
        public async Task<ApiResult<List<SheepPurchaseResultDto>>> SearchSheepPurchase([FromQuery] SearchSheepPurchaseDto dto)
        {
            _logger.LogInformation("开始查询羊只采购信息");
            
            try
            {
                if (!ModelState.IsValid)
                {
                    _logger.LogWarning("查询羊只采购信息时模型验证失败");
                    return new ApiResult<List<SheepPurchaseResultDto>> 
                    { 
                        msg = "请求参数验证失败", 
                        code = ApiREunm.Fail 
                    };
                }

                var result = await _sheepPurchaseServices.SearchSheepPurchase(dto);
                _logger.LogInformation("羊只采购信息查询完成，返回 {Count} 条记录", result.data?.Count ?? 0);
                
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询羊只采购信息时发生异常: {Message}", ex.Message);
                return new ApiResult<List<SheepPurchaseResultDto>> 
                { 
                    msg = "查询羊只采购信息失败，请稍后重试", 
                    code = ApiREunm.Fail 
                };
            }
        }

        /// <summary>
        /// 测试连接
        /// </summary>
        /// <returns>测试结果</returns>
        [HttpGet("test")]
        public ApiResult TestConnection()
        {
            _logger.LogInformation("测试连接");
            return new ApiResult 
            { 
                msg = "连接正常", 
                code = ApiREunm.Ok,
                data = new { timestamp = DateTime.Now, message = "API服务正常运行" }
            };
        }

        /// <summary>
        /// 根据ID获取羊只采购详情
        /// </summary>
        /// <param name="id">羊只采购ID</param>
        /// <returns>羊只采购详情</returns>
        [HttpGet("detail/{id}")]
        public async Task<ApiResult<SheepPurchaseResultDto>> GetSheepPurchaseById(long id)
        {
            _logger.LogInformation("开始获取羊只采购详情，ID: {Id}", id);
            
            try
            {
                if (id <= 0)
                {
                    _logger.LogWarning("获取羊只采购详情时ID参数无效: {Id}", id);
                    return new ApiResult<SheepPurchaseResultDto> 
                    { 
                        msg = "ID参数无效", 
                        code = ApiREunm.Fail 
                    };
                }

                var result = await _sheepPurchaseServices.GetSheepPurchaseById(id);
                _logger.LogInformation("羊只采购详情获取完成，ID: {Id}", id);
                
                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取羊只采购详情时发生异常，ID: {Id}, Message: {Message}", id, ex.Message);
                return new ApiResult<SheepPurchaseResultDto> 
                { 
                    msg = "获取羊只采购详情失败，请稍后重试", 
                    code = ApiREunm.Fail 
                };
            }
        }
    }
} 